package com.zx.ms.test.springcloud.hystrixconsumer.service;

import com.netflix.hystrix.*;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import org.springframework.web.client.RestTemplate;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;

public class UserObservableCommand extends HystrixObservableCommand<String> {

    private RestTemplate restTemplate;
    private Long id;

    public UserObservableCommand(Setter setter,RestTemplate restTemplate,Long id){
        super(setter);
        this.restTemplate = restTemplate;
        this.id = id ;
    }


    public UserObservableCommand(RestTemplate restTemplate,Long id){

        super(HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("CommandKeyName")));
//        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName"))
//                .andCommandKey(HystrixCommandKey.Factory.asKey("CommandKeyName"))
//                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("ThreadPoolKey")));
        this.restTemplate = restTemplate;
        this.id = id;

    }

    @Override
    protected Observable<String> construct() {

        return Observable.create(new Observable.OnSubscribe<String>(){

            @Override
            public void call(Subscriber<? super String> subscriber) {
                try {
                    if(!subscriber.isUnsubscribed()){
                        String s = restTemplate.getForObject("http://HELLO-DEV/hello",String.class,id);
                        subscriber.onNext(s);
                        subscriber.onCompleted();
                    }
                } catch (Exception e){
                    subscriber.onError(e);
                }
            }
        });
    }

    @Override
    protected Observable<String> resumeWithFallback() {
        return Observable.error(new RuntimeException("u a error"));
    }

    /**
     * 重写设置缓存
     * @return
     */
    @Override
    protected String getCacheKey() {
        return String.valueOf(id);
    }

    /**
     * 清楚缓存 需要手动调用
     * @param id
     */
    public static void flushCache(Long id){
        HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey("CommandKeyName")
                , HystrixConcurrencyStrategyDefault.getInstance()).clear(String.valueOf(id));
    }
}
